import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

var router = new Router({
  routes: [{
      path: '/',
      redirect: '/login'
    },
    {
      path: '/home',
      component: resolve => require(['../components/common/Main.vue'], resolve),
      children: [{
          path: '/',
          meta: {
            // 添加该字段，表示进入这个路由是需要登录的
            requireAuth: true,
          },
          component: resolve => require(['../components/page/Home.vue'], resolve)
        },
        {
          path: '/d3_demo',
          meta: {
            // 添加该字段，表示进入这个路由是需要登录的
            requireAuth: true,
          },
          component: resolve => require(['../components/demo/NonVueLineChart.vue'], resolve)
        }
      ]
    },
    {
      path: '/login',
      component: resolve => require(['../components/page/Login.vue'], resolve)
    },
  ]
})

// 全局导航钩子
router.beforeEach((to, from, next) => {
  // 判断该路由是否需要登录权限

  if (to.meta.requireAuth) {
    console.log("require Auth");
    // 通过vuex state获取当前的token是否存在
    let token = localStorage.getItem('token');
    //let token = Vue.prototype.store.getters.curr_token;
    if (!isEmptyObject(token)) {
      console.log("!isEmptyObject curr_token:" + token);
      next();
    } else {
      console.log("isEmptyObject curr_token:" + token);
      next({
        path: '/new_login',
        query: {
          redirect: to.fullPath
        } // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    console.log("don't require Auth");
    next();
  }
})

function isEmptyObject(obj) {
  for (var key in obj) {
    return false;
  }
  return true;
}

export default router
